<template>
  <div class="add-shop-wrapper">
    <div class="add-shop-card">
      <h2>添加商家</h2>
      <form @submit.prevent="submitForm" class="shop-form">
        <!-- 商家名称（必填） -->
        <div class="form-group">
          <label for="businessName">商家名称 *</label>
          <input
              type="text"
              id="businessName"
              v-model="formData.businessName"
              placeholder="请输入商家名称"
              required
          />
        </div>

        <!-- 店主ID（必填，输入数字） -->
        <div class="form-group">
          <label for="businessOwnerId">店主ID *</label>
          <input
              type="number"
              id="businessOwnerId"
              v-model.number="formData.businessOwner.id"
              placeholder="请输入店主用户ID"
              required
          />
        </div>

        <!-- 商家地址（可选） -->
        <div class="form-group">
          <label for="businessAddress">商家地址</label>
          <input
              type="text"
              id="businessAddress"
              v-model="formData.businessAddress"
              placeholder="请输入商家地址（可选）"
          />
        </div>

        <!-- 商家说明（可选） -->
        <div class="form-group">
          <label for="businessExplain">商家说明</label>
          <input
              type="text"
              id="businessExplain"
              v-model="formData.businessExplain"
              placeholder="请输入商家说明（可选）"
          />
        </div>

        <!-- 商家图片链接（可选） -->
        <div class="form-group">
          <label for="businessImg">商家图片链接</label>
          <input
              type="url"
              id="businessImg"
              v-model="formData.businessImg"
              placeholder="请输入图片链接（可选）"
          />
        </div>

        <!-- 起送价（可选） -->
        <div class="form-group">
          <label for="startPrice">起送价（元）</label>
          <input
              type="number"
              step="0.01"
              id="startPrice"
              v-model.number="formData.startPrice"
              placeholder="请输入起送价（可选）"
          />
        </div>

        <!-- 配送费（可选） -->
        <div class="form-group">
          <label for="deliveryPrice">配送费（元）</label>
          <input
              type="number"
              step="0.01"
              id="deliveryPrice"
              v-model.number="formData.deliveryPrice"
              placeholder="请输入配送费（可选）"
          />
        </div>

        <!-- 提交与取消按钮 -->
        <div class="button-group">
          <button type="button" class="cancel-btn" @click="goBack">取消</button>
          <button type="submit" class="submit-btn" :disabled="isSubmitting">
            {{ isSubmitting ? '提交中...' : '添加商家' }}
          </button>
        </div>

        <!-- 消息提示 -->
        <p v-if="message" :class="['message', message.type]">{{ message.text }}</p>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();

// 表单数据对象
const formData = ref({
  businessName: '',              // 必填
  businessOwner: {               // 必填，对象
    id: null                     // 必填，数字
  },
  businessAddress: '',           // 可选
  businessExplain: '',           // 可选
  businessImg: '',               // 可选
  startPrice: null,              // 可选，数字
  deliveryPrice: null,           // 可选，数字
  // 其它字段如 id, createTime, deleted 等由后端处理，无需传
});

// 提交状态
const isSubmitting = ref(false);

// 消息提示
const message = ref(null);

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 提交表单
const submitForm = async () => {
  message.value = null;

  // 必填校验
  if (!formData.value.businessName.trim()) {
    message.value = { type: 'error', text: '请输入商家名称！' };
    return;
  }
  if (formData.value.businessOwner.id === null || formData.value.businessOwner.id <= 0) {
    message.value = { type: 'error', text: '请输入有效的店主ID！' };
    return;
  }

  try {
    isSubmitting.value = true;

    // 获取 JWT Token
    const token = sessionStorage.getItem('jwt');
    if (!token) {
      message.value = { type: 'error', text: '用户未登录！' };
      return;
    }

    // 构造请求体 —— 仅包含用户填写的字段
    const payload = {
      businessName: formData.value.businessName,
      businessOwner: {
        id: formData.value.businessOwner.id
      },
      ...(formData.value.businessAddress && { businessAddress: formData.value.businessAddress }),
      ...(formData.value.businessExplain && { businessExplain: formData.value.businessExplain }),
      ...(formData.value.businessImg && { businessImg: formData.value.businessImg }),
      ...(formData.value.startPrice !== null && { startPrice: formData.value.startPrice }),
      ...(formData.value.deliveryPrice !== null && { deliveryPrice: formData.value.deliveryPrice }),
    };

    // 发送 POST 请求到 /business
    const response = await axios.post('/businesses', payload, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token.slice(1,-1)}`
      }
    });

    if (response.status === 200 || response.status === 201) {
      message.value = { type: 'success', text: '商家添加成功！' };
      // 清空表单
      formData.value = {
        businessName: '',
        businessOwner: { id: null },
        businessAddress: '',
        businessExplain: '',
        businessImg: '',
        startPrice: null,
        deliveryPrice: null,
      };
      // 3秒后自动返回
      setTimeout(() => {
        router.go(-1);
      }, 3000);
    }
  } catch (err) {
    console.error('添加商家失败:', err);

    if (err.response) {
      // 服务器返回错误信息
      const errorMsg = err.response.data?.message || '添加商家失败';
      message.value = { type: 'error', text: errorMsg };
    } else if (err.request) {
      message.value = { type: 'error', text: '网络错误，请检查连接！' };
    } else {
      message.value = { type: 'error', text: '添加商家失败，请重试！' };
    }
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<style scoped>
/* 页面容器，垂直水平居中 */
.add-shop-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

/* 卡片容器 */
.add-shop-card {
  width: 100%;
  max-width: 600px;
  padding: 30px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  color: #333;
  margin-bottom: 24px;
}

.shop-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

label {
  font-weight: bold;
  color: #555;
}

input {
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  transition: border-color 0.3s;
}

input:focus {
  outline: none;
  border-color: #007bff;
}

/* 按钮样式 */
.button-group {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.submit-btn {
  flex: 1;
  padding: 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:hover:not(:disabled) {
  background-color: #0056b3;
}

.submit-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.cancel-btn {
  flex: 1;
  padding: 12px;
  background-color: #f0f0f0;
  color: #333;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}

/* 消息提示样式 */
.message {
  margin-top: 15px;
  padding: 12px;
  border-radius: 6px;
  text-align: center;
  font-size: 14px;
}

.message.success {
  background-color: #e6ffed;
  color: #1a7324;
  border: 1px solid #b7eb8f;
}

.message.error {
  background-color: #ffebee;
  color: #c62828;
  border: 1px solid #ffa4a4;
}
</style>